package com.dy.security.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.google.code.kaptcha.Producer;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @ClassName:
 * @Author: dingyu
 * @Desctiption: (描述) 获取图形验证码控制器
 * @Date: 2022/3/31 13:24
 * @Version 1.0 (版本)
 */
@RestController
@RequiredArgsConstructor
public class CaptchaController {

    private final DefaultKaptcha defaultKaptcha;

    /**
     * 获取图形验证码
     * @return
     */
    @GetMapping("/kaptcha.jpg")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //设置内容类型
        response.setContentType("image/jpeg");
        //设置验证码文本
        String text = defaultKaptcha.createText();
        //将验证码设置进session中
        request.getSession().setAttribute("kaptcha", text);
        //创建验证码图片
        BufferedImage image = defaultKaptcha.createImage(text);
        //获取响应输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //将图片验证码写入输出流中
        ImageIO.write(image, "jpg", outputStream);
        //推送并关闭响应输出流
        try{
            outputStream.flush();
        }finally {
            outputStream.close();
        }
    }
}
